'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 科技管理
 * @author sundbcn@gmail.com (sun debing)
 */

var _ = require('lodash');
var async = require('async');
var moment = require('moment');
var Code = require('../../../consts/code');
var moduleType = require('../../../consts/moduleType');
var operationType = require('../../../consts/operationType');
var configUtil = require('../../../util/configUtil');
var PlayerManager = require('../../../libs/playerManager');
var techService = require('../../../services/techService');
var taskService = require('../../../services/taskService');
var roleService = require('../../../services/roleService');
var techConf = require('../../../config/techConf');
var buildType = require('../../../consts/buildType');
var buildService = require('../../../services/buildService');
var techType = require('../../../consts/techType.js');
var unionGroupModel = require('../../../models/unionGroupModel.js');
var unionHelpModel = require('../../../models/unionHelpModel.js');
var haveHelpModel = require('../../../models/haveHelpModel.js');
var unionTechType = require('../../../consts/unionTechType.js');
var unionTechService = require('../../../services/unionTechService.js');
var unionGroupMgr = require('../../../mgr/unionGroupMgr.js');
var haveHelpMgr = require('../../../mgr/haveHelpMgr.js');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

/**
 * 查询玩家科技列表(或者在登录时，直接推送到客户端)
 * @param  {[type]} msg     [description]
 * @param  {[type]} session [description]
 * @param  {[type]} next    [description]
 * @return {[type]}     [description]
 */
Handler.prototype.list = function (msg, session, next) {
    var role_id = session.uid;
    var tech_class = msg.tech_class;

    if (!tech_class || (tech_class !== 1 && tech_class !== 2 && tech_class !== 3)) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var tech_list = [];
    var up_tech_id;
    var up_tech_start_tm;
    var up_tech_end_tm;

    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [

            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['tech', 'build', 'role', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var tech_model = player_manager.tech;
                up_tech_id = tech_model.up_tech_id;
                up_tech_start_tm = tech_model.up_tech_start_tm;
                up_tech_end_tm = tech_model.up_tech_end_tm;
                var techIdList = techConf.getTechIdList(tech_class);
                _.each(techIdList, function (tech_id) {
                    var can_up = (_isTechCanUp(player_manager, tech_id, false) == Code.OK) ? 1 : 0;
                    var tech_level = tech_model.getTechLvl(tech_id);
                    tech_list.push({
                        tech_id: tech_id,
                        tech_level: tech_level,
                        can_up: can_up
                    });
                });

                cb();
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }

            return next(null, {
                code: Code.OK,
                result: {
                    'tech_list': tech_list,
                    'up_tech_id': up_tech_id,
                    'up_tech_start_tm': up_tech_start_tm,
                    'up_tech_end_tm': up_tech_end_tm
                }
            });
        }
    );
};

/**
 * 升级科技
 * @param  {[type]} msg     [description]
 * @param  {[type]} session [description]
 * @param  {[type]} next    [description]
 * @return {[type]}     [description]
 */
Handler.prototype.upTech = function (msg, session, next) {
    var role_id = session.uid;
    var tech_id = msg.tech_id;
    var start_time = 0;
    var end_time = 0;

    if (!tech_id) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [

            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['tech', 'role', 'build', 'accrued', 'task', 'daily_task', 'achieve'],
                    cb
                );
            },
            function (cb) {
                unionTechService.getUnionTechValue(player_manager, unionTechType.UNION_TECH_205, cb);
            },
            function (union_tech_value, cb) {
                var tech_model = player_manager.tech;
                var role_model = player_manager.role;

                // 判断科技队列状态
                if (tech_model.up_tech_id !== 0) {
                    return next(null, {
                        code: Code.TECH_QUE_BUSY
                    });
                }
                // 判断升级条件
                var ret_code = _isTechCanUp(player_manager, tech_id, true);
                if (ret_code != Code.OK) {
                    return next(null, {
                        code: ret_code
                    });
                }
                var next_tech_lvl = tech_model.getTechLvl(tech_id) + 1;
                var tech_lvl_info = techConf.getTechLvlConf(tech_id, next_tech_lvl);
                if (!tech_lvl_info) {
                    //科技达到顶级或无效的科技ID
                    return next(null, {
                        code: Code.TECH_REACH_TOP_LVL
                    });
                }
                // 扣减所需资源
                role_model.gold -= tech_lvl_info.cost_gold;
                role_model.food -= tech_lvl_info.cost_food;
                // 所需时间
                var need_time = tech_lvl_info.cost_time;
                var tech_eff = tech_model.getEffByTechType(techType.TECH_SPEED);

                if (tech_eff > 0) {
                    need_time = Math.ceil(need_time / (1 + tech_eff / 100) / (1 + union_tech_value / 100));
                }
                // 设置科技升级队列
                start_time = moment().unix();
                end_time = moment().unix() + need_time;
                tech_model.putToUpQue(tech_id, start_time, end_time);

                // 增加任务统计
                taskService.addUpgradeTech(player_manager);
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }

            return next(null, {
                code: Code.OK,
                result: {
                    tech_id: tech_id,
                    start_time: start_time,
                    end_time: end_time
                }
            });
        }
    );
};

/**
 * 秒升科技
 * @param  {[type]} msg     [description]
 * @param  {[type]} session [description]
 * @param  {[type]} next    [description]
 * @return {[type]}     [description]
 */
Handler.prototype.directUp = function (msg, session, next) {
    var role_id = session.uid;
    var role_model;
    var union_id = 0;
    var union_group_model;
    var tech_id = 0;
    var only_item = null;
    var help_list = [];
    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [

            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['tech', 'build', 'role', 'accrued', 'task', 'daily_task', 'achieve'],
                    cb
                );
            },
            function (cb) {
                role_model = player_manager.role;
                union_id = role_model.union_id;
                cb();
            },

            function (cb) {
                var tech_model = player_manager.tech;
                tech_id = tech_model.up_tech_id;

                // 判断科技队列状态
                if (!tech_model.up_tech_id) {
                    return next(null, {
                        code: Code.TECH_QUE_EMPTY
                    });
                } 

                // 剩余时间
                var remain_time = tech_model.up_tech_end_tm - moment().unix();
                if (remain_time <= 0) {
                    techService.refreshQue(tech_model, false, function () {
                        tech_model.save(function (err) {
                            next(err, {
                                code: Code.TECH_QUE_EMPTY
                            });
                        });
                    });
                    return;
                }

                // 扣除钻石
                var vip_lv = role_model.vip;
                var sub_diamond = buildService.getDirectDiamond(remain_time, vip_lv);
                if (!roleService.subDiamond(player_manager, moduleType.MDL_TECH, operationType.OPR_TECH_DIRECT_UP, sub_diamond)) {
                    return next(null, {
                        code: Code.USER_DIAMOND_NOT_ENOUGH
                    });
                }

                // 增加任务统计
                taskService.addUpgradeTech(player_manager);

                // 清除科技队列结束时间
                tech_model.up_tech_end_tm = 0;
                cb();
            },
            function (cb) {
                // 刷新科技队列
                var tech_model = player_manager.tech;
                techService.refreshQue(tech_model, false, cb);
            },
            function (cb) {
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            if (!!union_group_model) {
                union_group_model.save();
            }
            return next(null, {
                code: Code.OK
            });
        }
    );
};

/**
 * 判断指定科技是否可以升级
 * @param  {[type]} player_manager [description]
 * @param  {[type]} tech_id        [description]
 * @param  {[type]} res_check      [是否判断资源条件]
 * @return {[Code]}                [description]
 */
var _isTechCanUp = function (player_manager, tech_id, res_check) {
    // 前置科技/城堡等级/资源数量
    var tech_model = player_manager.tech;
    var role_model = player_manager.role;
    var build_model = player_manager.build;

    var tech_open_cnf = techConf.getTechOpenConf(tech_id);
    var next_tech_lvl = tech_model.getTechLvl(tech_id) + 1;
    var tech_lvl_info = techConf.getTechLvlConf(tech_id, next_tech_lvl);

    if (!tech_lvl_info) {
        return Code.TECH_REACH_TOP_LVL;
    }

    // 前置科技判断
    for (var i = 0; i < tech_open_cnf.length; i++) {
        var tech_cnf = tech_open_cnf[i];
        if (tech_cnf.need_tech_type !== 0) {
            var need_tech_curr_lvl = tech_model.getTechLvl(tech_cnf.need_tech_type);
            if (need_tech_curr_lvl < 1) {
                return Code.TECH_REQUIRE_TECH;
            }
        }
    }

    // 所需研究院等级判断
    var academy_build = build_model.getBuildByType(buildType.ACADEMY);
    var academy_lvl = academy_build.getLv();
    var need_academy_lvl = tech_lvl_info.need_academy_lvl;
    if (academy_lvl < need_academy_lvl) {
        return Code.TECH_REQUIRE_BUILD_LVL;
    }

    if (!res_check) {
        return Code.OK;
    }

    // 所需资源数量判断
    if (role_model.gold < tech_lvl_info.cost_gold || role_model.food < tech_lvl_info.cost_food) {
        return Code.TECH_REQUIRE_RESOURCE;
    }

    return Code.OK;
};
